<?php

use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\HttpMessage\Exception\HttpException;
use Ramsey\Uuid\Uuid;

if (! function_exists('reloadRoute')) {
    function reloadRoute()
    {
        $path = BASE_PATH . '/routes';
        $dirs = scandir($path);
        foreach ($dirs as $dir) {
            if ($dir != '.' && $dir != '..') {
                $routeFilePath = $path . "/{$dir}";
                $files = scandir($routeFilePath);
                foreach ($files as $file) {
                    if ($file != '.' && $file != '..') {
                        require_once $routeFilePath . '/' . basename($file);
                    }
                }
            }
        }
    }
}

if (!function_exists('success')) {
    function success($data = null, string $message = '成功'){
        return (new \Hyperf\HttpServer\Response())->json([
            'data' => $data,
            'message' => $message,
            'code' => \App\Constants\ErrorCode::CODE_TYPE_SUCCESS,
            'requestId' => Uuid::uuid4()->toString()
        ])->getBody()->getContents();
    }
}

if (!function_exists('error')) {
    function error($data = null, string $message = '失败',int $code = 0){
        return (new \Hyperf\HttpServer\Response())->json([
            'data' => $data,
            'message' => $message,
            'code' => empty($code) ? \App\Constants\ErrorCode::CODE_TYPE_ERROR_SYSTEM : -1,
            'requestId' => Uuid::uuid4()->toString()
        ])->getBody()->getContents();
    }
}

if (!function_exists('apiError')) {
    function apiError(string $message = '失败'){
        throw new \App\Exception\AppReturnException(error(message: $message));
    }
}

if (!function_exists('generateHashPassword')) {
    function generateHashPassword(string $password){
        return password_hash($password, PASSWORD_BCRYPT);
    }
}

if (!function_exists('jsonEncode')) {
    function jsonEncode(array $data){
        return json_encode($data,JSON_UNESCAPED_UNICODE);
    }
}

if (!function_exists('jsonDecode')) {
    function jsonDecode(string $json) : array{
        try {
            $res =  json_decode($json,true);
            if(is_array($res)){
                return $res;
            }
            return [];
        }catch (Exception $exception){
            apiError("非标准json");
        }

    }
}


if(!function_exists('md5Str')){
    function md5Str(){
        return md5(time().\Hyperf\Stringable\Str::random(10));
    }
}

if(!function_exists('categorizeArray')){
    function categorizeArray(array $data, string $key): array
    {
        $result = [];

        foreach ($data as $item) {
            // 获取当前项的分类值ErrorCode::CODE_TYPE_ERROR_LOGIN_EXPIRE
            $categoryValue = $item[$key];

            // 确保分类数组存在
            if (!isset($result[$categoryValue])) {
                $result[$categoryValue] = [];
            }

            // 将当前项添加到对应的分类数组中
            $result[$categoryValue][] = $item;
        }

        return $result;
    }
}


if(!function_exists('getOrganIdByOrganCode')){
    function getOrganIdByOrganCode($organCode = ''){
        // 这边默认通过用户信息去查当前用户所属机构
//        $userInfo = $this->
        return 1;
    }
}

if(!function_exists('getPuPvKey')){
    function getPuPvKey($bits = 1024){
        $privateKeyConfig = [
            "private_key_bits" => $bits,
            "private_key_type" => OPENSSL_KEYTYPE_RSA,
        ];
        // 生成私钥
        $privateKey = openssl_pkey_new($privateKeyConfig);

        // 导出私钥
        openssl_pkey_export($privateKey, $privateKeyString);

        // 获取公钥
        $publicKey = openssl_pkey_get_details($privateKey);
        $publicKeyString = $publicKey['key'];
        return [
            'pv_key' => $privateKeyString,
            'pu_key' => $publicKeyString
        ];
    }
}

if(!function_exists('x_dump')){
    function x_dump($data){
        // 获取调用栈信息
        $backtrace = debug_backtrace();
        // 获取调用该函数的文件和行号
        $caller = $backtrace[0];
        echo "Called from: " . $caller['file'] . " on line " . $caller['line'] . PHP_EOL;
        var_dump($data);
    }
}

if(!function_exists('transaction')){
    function transaction(callable $callback, $attempts = 1)
    {
        try {
            if ((int)Context::get('transaction_is_enable') === 0) { //避免重复事务
                Context::set('transaction_is_enable', 1);
                $result = Db::transaction($callback, $attempts);
                Context::set('transaction_is_enable', 0);
                return $result;
            }
            return call_user_func($callback);
        } catch (\Exception $e) {
            throw $e;
        } catch (\Throwable $throwable) {
            throw $throwable;
        } finally {
            Context::set('transaction_is_enable', 0);
        }
    }
//    # 示例
//    transaction(function () use ($id,$params) {
//        // 下架所有关联产品 并且 更新状态
//        OrgansGoodsMsq::getInc()->updateOrgansGoodsByEnterpriseLinkId($id,[
//            'status' => OrgansGoodsConstant::ORGANS_GOODS_STATUS['Closed']
//        ]);
//        OrgansEnterpriseLinkContro::getInc()->updateData($id,[
//            'status' => OrgansEnterpriseLinkConstant::ORGANS_ENTERPRISE_LINK_STATUS['Closed'],
//            'admin_user_id' => $params['admin_user_id'],
//            'admin_user_name' => $params['admin_user_name']
//        ]);
//    });
}
